package org.dromara.crawler.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.crawler.domain.TargetEvent;
import org.dromara.crawler.domain.TemplateManager;
import org.dromara.crawler.mapper.TemplateManagerMapper;
import org.dromara.crawler.service.TemplateManagerService;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class TemplateManagerServiceImpl extends ServiceImpl<TemplateManagerMapper, TemplateManager> implements TemplateManagerService {


    @Override
    public Boolean addEntity(TemplateManager templateManager) {
        LambdaQueryWrapper<TemplateManager> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TemplateManager::getTemplateName, templateManager.getTemplateName());
        if (baseMapper.selectCount(wrapper) > 0) {
            throw new ServiceException("模版名称重复！");
        }
        return save(templateManager);
    }

    @Override
    public TemplateManager findById(Long id) {
        return baseMapper.findById(id);
    }

    @Override
    public IPage<TemplateManager> queryByPage(TemplateManager templateManager, PageQuery pageQuery) {
        LambdaQueryWrapper<TemplateManager> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(ObjectUtil.isNotEmpty(templateManager.getTemplateName()), TemplateManager::getTemplateName, templateManager.getTemplateName());
        wrapper.eq(ObjectUtil.isNotEmpty(templateManager.getStatus()), TemplateManager::getStatus, templateManager.getStatus());
        wrapper.orderByDesc(TemplateManager::getCreateTime);
        return baseMapper.queryByPage(pageQuery.build(),wrapper);
    }
}
